/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <vector>
#include <map>
using namespace std;
class Solution {
    map<int, int> m;
    TreeNode *buildTree(vector<int> &preorder, int ph, int pt, vector<int> &inorder, int ih, int it){
        if (ph>pt || ih>it) return NULL;
        TreeNode *ret=new TreeNode(preorder[ph]);
        int index=m[preorder[ph]];
        ret->left=buildTree(preorder, ph+1, ph+index-ih, inorder, ih, index-1);
        ret->right=buildTree(preorder, ph+index-ih+1, pt, inorder, index+1, it);
        return ret;
    }
public:
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        m.clear();
        int n=preorder.size();
        for (int i=0;i<n;i++) m.insert(make_pair(inorder[i],i));
        return buildTree(preorder, 0, n-1, inorder, 0, n-1);
    }
};
